#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "app/stdcrc16/stdcrc16.h"
#include "app/stdcrc16/stdcrc16.c"

int main(int argc, char *argv[])
{
    FILE *f_bin, *f_operate;
    uint8_t *pdata;
    int data_size;
    unsigned short version, crc16;
    printf("app file: %s\n", argv[1]);
    sscanf(argv[2], "%04X", &version);
    printf("version = %04X\n", version);
    f_bin = fopen(argv[1], "rb");
    f_operate = fopen("update_file.bin", "wb");
    fseek(f_bin, 0, SEEK_END);
    data_size = ftell(f_bin);
    fseek(f_bin, 0, SEEK_SET);
    pdata = (uint8_t*)malloc(data_size);
    fread(pdata, data_size, 1, f_bin);
    fwrite(pdata, data_size, 1, f_operate);
    fflush(f_operate);
    crc16 = CRC16_MODBUS(pdata, data_size);
    free(pdata);
    fclose(f_bin);
    fwrite(&data_size, 4, 1, f_operate);
    fwrite(&version, 2, 1, f_operate);
    fwrite(&crc16, 2, 1, f_operate);
    fwrite("ZDS3", 4, 1, f_operate);
    fflush(f_operate);
    fclose(f_operate);
    return 0;
}
